package com.example.chao.configs;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: WangYongChao
 * @Date: 2021/08/05/21:14
 * @Description: swagger框架knife加强版
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

        @Value("8080")
        private String port;

        @Value("chao")
        private String application;

        // 定义分隔符
        private static final String splitor = ";";

        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(basePackage("com.example.chao.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }

        @SuppressWarnings("deprecation")
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口测试")
                    .description("采集系统相关API文档")
                    .termsOfServiceUrl("http://localhost:"+ port + "/" + application + "/swagger-ui.html")
                    .contact("王永超")
                    .version("1.0")
                    .build();
        }

        public static Predicate<RequestHandler> basePackage(final String basePackage) {
            return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
        }

        private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
            return input -> {
                // 循环判断匹配
                for (String strPackage : basePackage.split(splitor)) {
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            };
        }

        private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
            return Optional.fromNullable(input.declaringClass());
        }
}
